#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
@ author:konnlee
@ time  :2020/5/11 19:46
@ School:BESTI
"""
import socket
import os
import json
import struct
import hashlib
from my_des_c import des_encrypt


if __name__ == "__main__":
    client = socket.socket()
    client.connect(("127.0.0.1", 8001))
    while True:
        while True:
            md5 = hashlib.md5()
            cmd = input("请输入命令:")  # put 1.jpg
            if cmd == "exit":
                exit(0)
            try:
                action, filename = cmd.strip().split(' ')
                filesize = os.path.getsize(filename)
            except:
                print("命令错误或找不到文件")
                break

            file_info = {
                "action": action,
                "filename": filename,
                "filesize": filesize,
            }
            file_info_bytes = json.dumps(file_info).encode()
            len_header = len(file_info_bytes)
            res = struct.pack("i", len_header)
            client.send(res)
            client.send(file_info_bytes)

            # 发送文件数据
            with open(filename, 'rb') as f:
                for line in f:
                    client.send(des_encrypt(line))
                    print('\r', 'Successfully send:', des_encrypt(line).decode(), end="")
                    md5.update(line)
            print(client.recv(1024).decode())
            client.send((md5.hexdigest()).encode())
            print(client.recv(1024).decode())
